import { isNumber, reverseStr } from './utils'

const numbers = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const integerUnits = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '兆']
const integerUnitsExtension = ['元', '零', '零', '零', '万', '零', '零', '零', '亿', '零', '零', '零', '兆']

const decimalUnits = ['角', '分', '毫', '厘']
const INTEGER = '整'
const EXTENSION = '元'

export function formatterZH(money, decimalLength = 2) {
  if (!isNumber(money)) return money
  return format(money, decimalLength)
}

function format(money, decimalLength) {
  money = +money.toFixed(decimalLength)
  if (!money) return '零元整'
  const moneyStr = money + ''
  let suffix = '',
    integerStr,
    decimalStr
  if (hasDecimal(moneyStr)) {
    ;[integerStr, decimalStr] = moneyStr.split('.')
  } else {
    integerStr = moneyStr
    suffix += INTEGER
  }
  return formatInteger(integerStr) + formatDecimal(decimalStr, integerStr) + suffix
}

function formatInteger(integerStr) {
  var re = EXTENSION
  if (integerStr) {
    if (integerStr === '0') return ''
    integerStr = reverseStr(integerStr).slice(0, 13)
    let i = 0
    while (i < integerStr.length) {
      ;+integerStr[i] ? (re = numbers[integerStr[i]] + integerUnits[i] + re) : (re = addIntegerUnitsExtension(i, re))
      i++
    }
  }
  return re
}

function addIntegerUnitsExtension(index, str) {
  return integerUnitsExtension[index] &&
    str[0] &&
    integerUnitsExtension[index] !== str[0] &&
    !integerUnitsExtension.filter((item) => item !== '零').includes(str[0])
    ? integerUnitsExtension[index] + str
    : str
}

function formatDecimal(decimalStr, integerStr) {
  var re = ''
  if (decimalStr) {
    let length = decimalStr.length
    while (length) {
      length--
      ;(integerStr !== '0' || +decimalStr[length]) && (re = numbers[decimalStr[length]] + decimalUnits[length] + re)
    }
  }
  return re
}

function hasDecimal(moneyStr) {
  return moneyStr.includes('.')
}
